package class01;

import java.util.IllegalFormatCodePointException;

/**
 * @author zhangchaoliang
 * create 2022
 */
public class aw1 {

    public static int getLessIndex(int[] arr) {
        if (arr == null || arr.length == 0)
            return -1;
        if (arr.length == 1 || arr[0] < arr[1])
            return 0;
        if (arr[arr.length - 1] < arr[arr.length - 2])
            return arr.length - 1;
        int left = 1;
        int right = arr.length - 2;
        int mid=0;

        while (left < right) {
            mid = left + ((right - left) >> 1);
            if (arr[mid] > arr[mid - 1]) {
                right = mid - 1;
            } else if (arr[mid] > arr[mid + 1]) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return left;
    }


    public static boolean test(int[] arr, int index) {
        if (arr == null || arr.length == 0)
            return true;
        if (index == 0)
            return arr.length == 1 || arr[index] < arr[index + 1];
        if (index == arr.length - 1)
            return arr[arr.length - 1] < arr[arr.length - 2];
        return arr[index] < arr[index - 1] && arr[index] < arr[index + 1];
    }

    public static int[] RandomArrays(int maxSize, int maxValue) {
        int[] arr = new int[(int) (maxSize * Math.random() + 1)];
        arr[0] = (int) ((maxValue + 1) * Math.random()) - (int) ((maxValue + 1) * Math.random());
        for (int i = 1; i < arr.length; i++) {
            do {
                arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) ((maxValue + 1) * Math.random());
            } while (arr[i] == arr[i - 1]);
        }
        return arr;
    }

    public static void main(String[] args) {
        int testTime = 500000;
        int maxSize = 100;
        int maxValue = 100;
        System.out.println("测试开始！");
        for (int i = 0; i < testTime; i++) {
            int[] arr = RandomArrays(maxSize, maxValue);
            int index = getLessIndex(arr);
            if (!test(arr, index)) {
                System.out.println("出错了！");
                break;
            }
        }
        System.out.println("测试成功！");
    }
}
